package com.dmall.chapter06.section05;

public class LeetCode1020 {

    private int R, C;
    private int[][] dirs = {{-1, 0}, {0, 1}, {1, 0}, {0, -1}};

    public int numEnclaves(int[][] A) {
        R = A.length;
        C = A[0].length;

        for (int i = 0; i < R; i++) {
            dfs(A, i, 0);
            dfs(A, i, C - 1);
        }

        for (int i = 0; i < C; i++) {
            dfs(A, 0, i);
            dfs(A, R - 1, i);
        }

        int res = 0;
        for (int i = 0; i < R; i++) {
            for (int j = 0; j < C; j++) {
                if (A[i][j] == 1) {
                    res++;
                }
            }
        }

        return res;
    }

    private void dfs(int[][] grid, int x, int y) {
        if (grid[x][y] == 0) {
            return;
        }
        grid[x][y] = 0;
        for (int i = 0; i < dirs.length; i++) {
            int nextx = x + dirs[i][0];
            int nexty = y + dirs[i][1];
            if (inArea(nextx, nexty)) {
                dfs(grid, nextx, nexty);
            }
        }
    }

    private boolean inArea(int x, int y) {
        return x >= 0 && x < R && y >= 0 && y < C;
    }

    public static void main(String[] args) {
        // int[][] grid = {{0, 1, 1, 0}, {0, 0, 1, 0}, {0, 0, 1, 0}, {0, 0, 0, 0}};
        int[][] grid = {{0, 0, 0, 0}, {1, 0, 1, 0}, {0, 1, 1, 0}, {0, 0, 0, 0}};
        LeetCode1020 leetCode1020 = new LeetCode1020();
        System.out.println(leetCode1020.numEnclaves(grid));
    }
}
